package com.zhang.controller;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.zhang.entity.*;
import com.zhang.service.AddressService;
import com.zhang.service.OrderService;
import com.zhang.service.impl.AddressServiceImpl;
import com.zhang.service.impl.OrderServiceImpl;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import redis.clients.jedis.Jedis;

import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;

@Controller
@RequestMapping("/order")
public class OrderController {
    AddressService as = new AddressServiceImpl();
    OrderService os = new OrderServiceImpl();

    @RequestMapping("/addressList")
    public String addressList(HttpSession session, Model model) throws JsonProcessingException {
        User user = (User)session.getAttribute("user");
        Jedis jedis = new Jedis("192.168.111.107",6379);
        String s = jedis.get(String.valueOf(user.getId()));
        ObjectMapper mapper=new ObjectMapper();
        User user1 = mapper.readValue(s, User.class);
        List<Address> addressList = as.selectAll(user1.getId());
        model.addAttribute("addressList",addressList);
        return "forward:/order/address_form.jsp";
    }

    @RequestMapping("/createOrder")
    public String createOrder(int address,HttpSession session){
        User user = (User)session.getAttribute("user");
        Cart cart = (Cart)session.getAttribute("cart");
        Order order = new Order(null,cart.getTotalMoney(),null,0,address,user.getId());

        Set<Map.Entry<Integer, CartItem>> entries = cart.getBuyMap().entrySet();
        order.setOrderItemList(new ArrayList<>());
        List<OrderItem> orderItemList = order.getOrderItemList();
        for(Map.Entry<Integer,CartItem> entry:entries){
            OrderItem orderItem = new OrderItem(null,entry.getKey(),null,entry.getValue().getCount(),entry.getValue().getProduct().getDangprice());
            orderItemList.add(orderItem);
        }
        os.insert(order);
        session.removeAttribute("cart");
        return "redirect:/order/order_ok.jsp?orderId="+order.getId()+"&totalMoney="+cart.getTotalMoney();
    }

    @RequestMapping("/showAll")
    public String showAll(HttpSession session,Model model){
        User user = (User)session.getAttribute("user");
        List<Order> orderList = os.selectAll(user.getId());
        model.addAttribute("orderList",orderList);
        return "forward:/order/my_order.jsp";
    }

    @RequestMapping("/changeState")
    public String changeState(int out_trade_no){
        os.changeState(out_trade_no);
        return "redirect:/order/showAll.do";
    }
}
